package com.itheima.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.commit.R;
import com.itheima.commit.CacheService;
import com.itheima.dto.DishDto;
import com.itheima.mapper.DishMapper;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private CacheService cacheService;
    @Transactional
    @Override
    public R<String> add(DishDto dishDto) {
        //因为继承了dish表，所有可以先添加除dishid的其他字段
        this.save(dishDto);
        //这里因为已经添加，所有菜品id有值了
        Long id = dishDto.getId();
        //获取flavors的值
        List<DishFlavor> flavors = dishDto.getFlavors();
        //给flavors中的dishid赋值
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(id);
        }
        //给口味表赋值
        dishFlavorService.saveBatch(flavors);

        Set<String> keys = cacheService.keys("dish*");
        cacheService.delete(keys);

        return R.success("添加成功");
    }

    @Override
    public R<IPage> selectP(Integer page,Integer pageSize , String name) {
        //设置页数
        IPage<DishDto> page1 = new Page<>(page,pageSize);
        //调用方法查询出所有的数据
        List<DishDto> dishDtos = dishMapper.selectP(page1, name);
        //将数据封装到Page中
        page1.setRecords(dishDtos);

        return R.success(page1);
    }

    @Override
    public R<DishDto> get(Long id) {
        Dish byId = this.getById(id);
        DishDto dishDto = new DishDto();

        BeanUtils.copyProperties(byId,dishDto);

        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> list = dishFlavorService.list(wrapper);

        dishDto.setFlavors(list);
        return R.success(dishDto);
    }

    @Transactional
    @Override
    public R<String> update(DishDto dishDto) {
        this.updateById(dishDto);

        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(wrapper);

        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavors);

        Set<String> keys = cacheService.keys("dish*");
        cacheService.delete(keys);

        return R.success("修改成功");
    }

    @Override
    public R<String> upda(int s ,Long[] ids) {
        log.info("s={}",s);
        for (Long id : ids) {
            Dish byId = getById(id);
            byId.setStatus(s);
            updateById(byId);

            Set<String> keys = cacheService.keys("dish*");
            cacheService.delete(keys);
        }
        return R.success("修改成功");
    }

    @Override
    public R<String> delete(Long[] ids) {
        for (Long id : ids) {
            Dish byId = getById(id);
            if (byId.getStatus() == 0) {
                LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(DishFlavor::getDishId,id);
                dishFlavorService.remove(wrapper);

                this.removeById(byId);

                Set<String> keys = cacheService.keys("dish*");
                cacheService.delete(keys);

                return R.success("删除成功");
            }
        }
        return R.error("菜品正在售卖，不能删除");
    }

    @Override
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDto = null;

        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();

        log.info("key{}",key);

        String s = cacheService.get(key);

        if (s != null) {
            dishDto = JSON.parseArray(s,DishDto.class);
            return R.success(dishDto);
        }

        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(dish!=null,Dish::getCategoryId,dish.getCategoryId());
        wrapper.orderByAsc(Dish::getSort);

        List<Dish> list = list(wrapper);

        dishDto = list.stream().map(item->{
            DishDto dishDto1 = new DishDto();
            BeanUtils.copyProperties(item,dishDto1);

            Long id = item.getId();
            LambdaQueryWrapper<DishFlavor> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(DishFlavor::getDishId,id);

            List<DishFlavor> list1 = dishFlavorService.list(wrapper1);
            dishDto1.setFlavors(list1);
            return dishDto1;
        }).collect(Collectors.toList());

        cacheService.setEx(key,JSON.toJSONString(dishDto),5, TimeUnit.MINUTES);

        return R.success(dishDto);

    }


}
